<?php
$launchdate = strtotime('2013-04-28');//has to be a sunday
$sevendays = 7 * 24 * 3600;
$starthdate = $launchdate + $sevendays;

$today = strtotime(date("Y-m-d"));

$weeks = array();
while($starthdate < $today){
	$starthdate = $starthdate + $sevendays;
	$weekending = date('Y-m-d',$starthdate);
	$weeks[$weekending] = $weekending;
}

krsort($weeks);//reverse the array order so that it picks dates from newest to oldest dates
$timesheetsrearranged = array();
foreach($timesheets as $timesheet):
	$timesheetsrearranged[$timesheet['Timesheet']['title']][$timesheet['Timesheet']['user_id']] = $timesheet['Timesheet'];
endforeach; 

$count = 0;

/*echo '<pre>';
print_r($timesheetsrearranged);
//print_r($weeks);
echo '</pre>';*/
?>


<table>
	<?php
	foreach($weeks as $starthdate => $weekending):?>
			<tr>
			<td colspan="2" class="client">Week ending: <?php echo $weekending; ?></td>
            </tr>
            <?php foreach($users as $user):
				if(array_key_exists($weekending, $timesheetsrearranged)){
					$timesheetbyuser = $timesheetsrearranged[$weekending];
				}else{
					$timesheetbyuser = array();
				}
				
				$userid = $user['User']['id'];
				if(array_key_exists($userid, $timesheetbyuser))
					$action = $this->Html->link('view',array('controller' => 'timesheets', 'action' => 'view', $timesheetsrearranged[$weekending][$userid]['id']));
				else
					$action = 'overdue';?>
            	
                <tr>
                <td><?php echo $user['User']['username']; ?></td>
                <td><?php echo $action; ?></td>
                </tr>
            <?php endforeach; ?>
        
	<?php
		  $count++; ?>
	<?php endforeach; ?>
    <?php unset($weeks); ?>
  
</table>